// pages/village/index.js
import {
  getTopicList,
  collectList
}
from '../../api/ChatTopicController'
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    active: 'recommend',
    topicList: [], //帖子列表
    collectList: [], //关注列表
    params: {
      cityCode: app.userLocation.cityCode || 156340100,
      pageNum: 1,
      pageSize: 10,
      userId: wx.getStorageSync('userId') || '0'
    },
    collectParams: {
      pageNum: 1,
      pageSize: 10
    },
    totalPage: 0, //总页数
    collectTotalPage: 0, //关注总页数
    view: false,
    fLike: false, //首次进入关注页面
    isReachBottom: false, //是否上拉刷新
    dataCompleted: false, //数据加载完成
    collectCompleted: false, //关注数据加载完成
    scrollTop: 0,
    playId: undefined,
    _this: undefined,
  },
  //用户下拉动作
  async onScrollRefresh() {
    if (this.data.active === 'recommend') {
      try {
        this.setData({
          'params.pageNum': 1,
          dataCompleted: false
        })
        await this.getTopicList(this.data.params)
      } catch (error) {} finally {
        this.setData({
          triggered: false,
        })
      }
    } else {
      try {
        this.setData({
          'collectParams.pageNum': 1,
          collectCompleted: false
        })
        await this.getCollectList()
      } catch (error) {} finally {
        this.setData({
          triggered: false,
        })
      }
    }
  },
  //上拉刷新
  async onReachBottom() {
    if (this.data.isReachBottom) return
    if (this.data.active === 'recommend') {
      if (this.data.totalPage <= this.data.params.pageNum) return this.setData({
        dataCompleted: true
      })
      this.setData({
        isReachBottom: true,
        'params.pageNum': this.data.params.pageNum + 1
      })
      try {
        await this.getTopicList()
      } catch (error) {

      } finally {
        this.setData({
          isReachBottom: false
        })
      }
    } else {
      try {
        this.setData({
          isReachBottom: true
        })
        await this.getCollectList()
      } catch (error) {

      } finally {
        this.setData({
          isReachBottom: false
        })
      }
    }
  },
  //tab切换
  async tabsChange(ev) {
    this.setData({
      scrollTop: 0,
      active: ev.detail.name
    })
    //切换tab暂停上个页面的视频
    if (this.data.playId) {
      wx.createVideoContext('video' + this.data.playId, this.data._this).pause()
      this.setData({
        playId: undefined,
        _this: undefined
      })
    }
    if (this.data.active === 'recommend') {
      this.setData({
        'params.pageNum': 1,
        dataCompleted: false
      })
      await this.getTopicList(this.data.params)
    } else {
      this.setData({
        'collectParams.pageNum': 1,
        collectCompleted: false,
        fLike: true
      })
      await this.getCollectList()
    }
  },
  //获取帖子列表
  async getTopicList() {
    this.setData({
      'params.cityCode': app.userLocation.cityCode || 156340100
    })
    const res = await getTopicList(this.data.params)
    // res.list.forEach(ele => ele.createTime = wx.utils.formatMsgTime(ele.createTime))
    const newList = res.list.map(({
      createTime,
      likeCount,
      collectCount,
      rewardSCoin,
      replyCount,
      ...item
    }) => ({
      createTime: wx.utils.formatMsgTime(createTime),
      likeCount: wx.utils.formatNumber(+likeCount),
      collectCount: wx.utils.formatNumber(+collectCount),
      rewardSCoin: wx.utils.formatNumber(+rewardSCoin),
      replyCount: wx.utils.formatNumber(+replyCount),
      ...item
    }))
    if (this.data.isReachBottom) {
      this.setData({
        topicList: [...this.data.topicList, ...newList],
        totalPage: res.totalPage
      })
    } else {
      this.setData({
        topicList: newList,
        totalPage: res.totalPage
      })
    }
  },
  //获取关注帖子列表
  async getCollectList() {
    if (!wx.getStorageSync('userId') || this.data.collectCompleted) return
    const res = await collectList({
      pageNum: this.data.collectParams.pageNum,
      pageSize: this.data.collectParams.pageSize,
      userId: wx.getStorageSync('userId')
    })
    // res.list.forEach(ele => ele.createTime = wx.utils.formatMsgTime(ele.createTime))
    const newList = res.list.map(({
      createTime,
      likeCount,
      collectCount,
      rewardSCoin,
      replyCount,
      ...item
    }) => ({
      createTime: wx.utils.formatMsgTime(createTime),
      likeCount: wx.utils.formatNumber(+likeCount),
      collectCount: wx.utils.formatNumber(+collectCount),
      rewardSCoin: wx.utils.formatNumber(+rewardSCoin),
      replyCount: wx.utils.formatNumber(+replyCount),
      ...item
    }))
    this.setData({
      collectList: this.data.isReachBottom ? [...this.data.collectList, ...newList] : newList,
      collectTotalPage: res.totalPage,
      'collectParams.pageNum': this.data.collectParams.pageNum + 1
    })
    if (this.data.collectParams.pageNum > this.data.collectTotalPage) {
      this.setData({
        collectCompleted: true
      })
    }
  },
  //更新操作数据
  updateStatus(ev) {
    if (ev.detail.type === 'like') {
      this.data.topicList.forEach((ele, index) => {
        if (ele.topicId === ev.detail.topicId) {
          this.setData({
            ['topicList[' + index + '].hasLike']: ev.detail.has,
            ['topicList[' + index + '].likeCount']: ev.detail.count
          })
        }
      })
    } else {
      this.data.topicList.forEach((ele, index) => {
        if (ele.topicId === ev.detail.topicId) {
          this.setData({
            ['topicList[' + index + '].hasCollect']: ev.detail.has,
            ['topicList[' + index + '].collectCount']: ev.detail.count
          })
        }
      })
    }
  },
  //更新关注列表数据
  updateFollowStatus(ev) {
    if (ev.detail.type === 'like') {
      this.data.collectList.forEach((ele, index) => {
        if (ele.topicId === ev.detail.topicId) {
          this.setData({
            ['collectList[' + index + '].hasLike']: ev.detail.has,
            ['collectList[' + index + '].likeCount']: ev.detail.count
          })
        }
      })
    } else {
      this.data.collectList.forEach((ele, index) => {
        if (ele.topicId === ev.detail.topicId) {
          this.setData({
            ['collectList[' + index + '].hasCollect']: ev.detail.has,
            ['collectList[' + index + '].collectCount']: ev.detail.count
          })
        }
      })
    }
  },
  //控制视频播放
  play(e) {
    const id = e.detail.id
    const _this = e.detail._this
    if (!this.data.playId) {
      this.setData({
        playId: id,
        _this,
      })
    }
    if (this.data.playId && this.data.playId !== id) {
      wx.createVideoContext('video' + this.data.playId, this.data._this).pause()
      this.setData({
        playId: id,
        _this
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //动态获取右上角胶囊按钮距离顶部位置
    const menu = wx.getMenuButtonBoundingClientRect();
    this.setData({
      top: menu.top - 5
    })
    this.getTopicList()
    this.getCollectList()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //接收消息角标
    wx.onSocketMessage((res) => {
      this.getTabBar().setData({
        count: app.count + 1
      })
      app.count = app.count + 1
    })
    if (wx.getStorageSync('userId')) this.setData({
      'params.userId': wx.getStorageSync('userId')
    })
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1,
        count: app.count
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})